package com.scsj.supermarket.view.activity.cooperationmodel;

import android.graphics.Point;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.scsj.supermarket.R;
import com.scsj.supermarket.base.GetCircleMasterImgBase;
import com.scsj.supermarket.bean.CircleMasterBean;
import com.scsj.supermarket.bean.NearByTradeAreaBean;
import com.scsj.supermarket.bean.RequestTobeCircleManBean;
import com.scsj.supermarket.event.FirstEvent;
import com.scsj.supermarket.presenter.GetCircleMasterPresenter;
import com.scsj.supermarket.utils.BaiduMapHelper;
import com.scsj.supermarket.utils.RxBus;
import com.scsj.supermarket.utils.SkipUtils;
import com.scsj.supermarket.view.activity.baseactivitymodel.BaseActivity;

import java.util.ArrayList;
import java.util.List;

import es.dmoral.toasty.Toasty;
import okhttp3.RequestBody;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * 圈主注册1
 */
public class BusinessCircleMasterRegisterActivity extends BaseActivity implements View.OnClickListener, GetCircleMasterImgBase.IView {

    private Button mNextBtn;
    private MapView mapView;
    private ScrollView mScrollView;
    private ImageView middleIv, resetIv;
    private BaiduMap mBaiduMap;
    private float zoom = 16;
    private GetCircleMasterPresenter getCircleMasterPresenter;
    private List<CircleMasterBean.DataBean> circleMarkLists = new ArrayList<>();

    private TextView circleNameTv;
    private TextView circleAddressTv;
    private TextView circleRadiusTv;
    private TextView circleMoneyTv;
    private RequestTobeCircleManBean.TradeAreaApplyBean tradeAreaApplyBean;

    @Override
    protected void createView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_business_circle_master_register);
//        ScreenAdapterTools.getInstance().loadView((ViewGroup) getWindow().getDecorView());
        //ScreenAdapterTools.getInstance().reset(this);//如果希望android7.0分屏也适配的话,加上这句
        initToolbar();
        setToolbarTitle("圈主注册");
        hasBack(true);
        initView();
    }

    @Override
    protected void initView() {
        getCircleMasterPresenter = new GetCircleMasterPresenter(this);
        tradeAreaApplyBean= new RequestTobeCircleManBean.TradeAreaApplyBean();
        mapView = findViewById(R.id.map);
        mBaiduMap = mapView.getMap();
        mNextBtn = (Button) findViewById(R.id.bcmr_next_btn);
        middleIv = findViewById(R.id.middle_location_iv);
        mScrollView = findViewById(R.id.scroll_view);

        circleNameTv= findViewById(R.id.business_circle_name_tv);
        circleAddressTv= findViewById(R.id.business_circle_address_tv);
        circleRadiusTv= findViewById(R.id.business_circle_radius_tv);
        circleMoneyTv= findViewById(R.id.business_circle__tv);
        //百度地图初始化
        BaiduMapHelper
                .getInstance()
                .init(mapView)
                .params(this)
                .showLocation();
        mapView.getChildAt(0).setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    //允许ScrollView截断点击事件，ScrollView可滑动
                    mScrollView.requestDisallowInterceptTouchEvent(false);
                } else {
                    //不允许ScrollView截断点击事件，点击事件由子View处理
                    mScrollView.requestDisallowInterceptTouchEvent(true);
                }
                return false;
            }
        });

    }
    @Override
    protected void initListener() {
        mNextBtn.setOnClickListener(this);
        /**
         地图状态改变监听
         */
        mBaiduMap.setOnMapStatusChangeListener(new BaiduMap.OnMapStatusChangeListener() {
            @Override
            public void onMapStatusChangeStart(MapStatus arg0) {
//                //地图状态改变，取消网络请求
//                if (cancelable!=null && !cancelable.isCancelled())
//                    cancelable.cancel();
//                mImageView.startAnimation(animation);
                startAnima();
            }

            @Override
            public void onMapStatusChangeStart(MapStatus mapStatus, int i) {

            }

            @Override
            public void onMapStatusChangeFinish(MapStatus arg0) {
                startAnima2();
                Point point = new Point();
                int[] location = new int[2];
                middleIv.getLocationOnScreen(location);
                point.x = location[0] - middleIv.getWidth() / 2;
                point.y = location[1];
                zoom = arg0.zoom;

                LatLng latLng = mBaiduMap.getProjection().fromScreenLocation(point);
                if (latLng.latitude != 0 && latLng.longitude != 0) {
                    //地图状态改变结束，请求网络操作，获取店铺信息
                    getLocationInfo(latLng.latitude, latLng.longitude, null);
                }
            }
            @Override
            public void onMapStatusChange(MapStatus arg0) {
                // TODO Auto-generated method stub
            }
        });
    }
    private void getLocationInfo(double latitude, double longitude, Object o) {

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("state", "-1");
        jsonObject.put("latitude", latitude);
        jsonObject.put("longitude", longitude);
        //jsonObject.put("name", "scsj");
        RequestBody requestBody = RequestBody.create(okhttp3.MediaType
                .parse("application/json;charset=utf-8"), jsonObject.toString());
        getCircleMasterPresenter.deliverData(requestBody);
    }

    @Override
    protected void initData() {
        RxBus.getDefault().toObservable(FirstEvent.class)
                //在io线程进行订阅，可以执行一些耗时操作
                .subscribeOn(Schedulers.io())
                //在主线程进行观察，可做UI更新操作
                .observeOn(AndroidSchedulers.mainThread())
                //观察的对象
                .subscribe(new Action1<FirstEvent>() {
                    @Override
                    public void call(FirstEvent firstEvent) {
                        if (firstEvent.getCode().equals("location")) {
                            Double lat = Double.parseDouble(firstEvent.getLatitude());
                            Double log = Double.parseDouble(firstEvent.getLongitude());
                            getLocationInfo(lat, log, null);
                        }
                    }
                });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bcmr_next_btn:
                Log.e("打印一下看看：：",tradeAreaApplyBean.getTradeAreaId()+"99999");
                SkipUtils.toBusinessCircleMasterRegister2(this,tradeAreaApplyBean);
                break;
            default:
                break;
        }
    }
    /**
     * 地图状态开始改变就开始执行动画start
     */
    private void startAnima() {
        final TranslateAnimation animation = new TranslateAnimation(0, 0, 0, -50);
        animation.setInterpolator(new LinearInterpolator());
        animation.setDuration(200);//设置动画持续时间
        animation.setRepeatCount(0);//设置重复次数
        animation.setFillAfter(true);
        middleIv.startAnimation(animation);
    }

    /**
     * 地图状态改变结束就开始执行动画finish
     */
    private void startAnima2() {
        final TranslateAnimation animation2 = new TranslateAnimation(0, 0, -50, 0);
        animation2.setInterpolator(new LinearInterpolator());
        animation2.setDuration(200);//设置动画持续时间
        animation2.setRepeatCount(0);//设置重复次数
        animation2.setFillAfter(true);
        middleIv.startAnimation(animation2);
    }

    @Override
    public void showSuccessMsg(String s, CircleMasterBean circleMasterBean) {
        //数据获取成功之后，添加覆盖物，同时刷新下方信息
        AddMarkAndRefreshUi(circleMasterBean);
    }

    @Override
    public void showErrorMsg(String s) {

    }
    private void AddMarkAndRefreshUi(CircleMasterBean circleMasterBean) {
        if (circleMasterBean.isSuccess() && circleMasterBean.getStatusCode() == 200) {
            circleMarkLists = circleMasterBean.getData();
            addMapIcon(circleMarkLists);
        }
    }

    private void addMapIcon(List<CircleMasterBean.DataBean> tradeAreaList) {
        /**
         * 每次添加覆盖物之前都要先移除覆盖物监听事件，防止点击事件多次执行
         */
        mBaiduMap.removeMarkerClickListener(onMarkerClickListener);
        mBaiduMap.clear();
        Bundle bundle = new Bundle();
        /**
         * 遍历外层商圈
         */
        for (int i = 0; i < tradeAreaList.size(); i++) {
            Marker marker;
            CircleMasterBean.DataBean dataBean = tradeAreaList.get(i);
            //定义Maker坐标点
            LatLng point = new LatLng(dataBean.getLatitude(), dataBean.getLongitude());
            //构建Marker图标
            int icon = R.mipmap.map_shop_circle_ic;
            //转换为BitMap
            BitmapDescriptor bitmap = BitmapDescriptorFactory
                    .fromResource(icon);
            //构建MarkerOption，用于在地图上添加Marker
            OverlayOptions option = new MarkerOptions()
                    .position(point)
                    .perspective(true)
                    .icon(bitmap);
            //在地图上添加Marker，并显示
            marker = (Marker) mBaiduMap.addOverlay(option);
            bundle.putSerializable("trade_click", dataBean);
            marker.setExtraInfo(bundle);
        }
        /**
         * 覆盖物点击事件
         */
        mBaiduMap.setOnMarkerClickListener(onMarkerClickListener);
    }

    /**
     * 自定义覆盖物监听类，用来控制覆盖物的监听与取消监听
     */
    BaiduMap.OnMarkerClickListener onMarkerClickListener = new BaiduMap.OnMarkerClickListener() {
        @Override
        public boolean onMarkerClick(Marker marker) {
            Bundle bundle = marker.getExtraInfo();
            if (bundle != null) {
                //商圈点击事件
                CircleMasterBean.DataBean dataBean = (CircleMasterBean.DataBean) bundle.getSerializable("trade_click");
                if (dataBean != null) {
                    //商圈名字
                    String circleName= dataBean.getName();
                   //商圈中心地址
                    String centerAddress= dataBean.getAddress();
                    //商圈半径
                    String circleRadius= String.valueOf(dataBean.getRadius());
                    //认购金额
                    String money= String.valueOf(dataBean.getDepositAmount());
                    //商圈id
                    String tradeAreaId= dataBean.getId();
                    tradeAreaApplyBean.setTradeAreaId(tradeAreaId);

                    if (circleName!=null){
                        circleNameTv.setText(circleName);
                    }else if (centerAddress!=null){
                        circleAddressTv.setText(centerAddress);
                    }else if (circleRadius!=null){
                        circleRadiusTv.setText(circleRadius);
                    }else if (money!=null){
                        circleMoneyTv.setText(money);
                    }
                }
            }
            return false;
        }
    };
}